package com.beviswong.themedemo

import android.app.Activity
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate

object ThemeManager {
    // 主题类型常量
    const val THEME_DEFAULT = 0
    const val THEME_DARK = 1
    const val THEME_LIGHT = 2

    private const val PREF_THEME = "pref_theme"
    private const val PREF_NAME = "theme_prefs"

    /**
     * 保存主题设置到SharedPreferences
     * @param context
     * @param themeType
     */
    fun saveTheme(context: Context, themeType: Int) {
        val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        prefs.edit().putInt(PREF_THEME, themeType).apply()
    }

    /**
     * 保存并立即为当前 Activity 应用主题
     * @param activity
     * @param themeType 主题类型
     */
    fun switchThemeNow(activity: Activity, themeType: Int) {
        activity.apply {
            saveTheme(this, themeType)
            finish()
            startActivity(intent)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                overrideActivityTransition(AppCompatActivity.OVERRIDE_TRANSITION_OPEN, 0, 0)
            } else {
                overridePendingTransition(0, 0)
            }
        }
    }

    /**
     * 从SharedPreferences获取保存的主题
     * @param context
     */
    fun getSavedTheme(context: Context): Int {
        val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        return prefs.getInt(PREF_THEME, THEME_DEFAULT)
    }

    /**
     * 如果不需要兼容夜间模式，则关闭，防止夜间模式导致资源混乱
     * @param themeType
     */
    fun closeNightMode(themeType: Int) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    }

    /**
     * 根据主题类型获取对应的主题样式资源
     * @param themeType
     */
    fun getThemeStyle(themeType: Int): Int {
        return when (themeType) {
            THEME_DEFAULT -> R.style.TDThemeDemo
            THEME_DARK -> R.style.TDDarkDemo
            THEME_LIGHT -> R.style.TDLightDemo
            else -> R.style.TDThemeDemo
        }
    }
}